//
//  WBComposeCell.swift
//  WeiboTen
//
//  Created by ItHeiMa on 2017/7/16.
//  Copyright © 2017年 itHeima. All rights reserved.
//

import UIKit
import SnapKit

protocol WBComposeCellDelegate: NSObjectProtocol {
    func addOrChangeImage(cell: WBComposeCell)
    func deleteImage(cell: WBComposeCell)
}

class WBComposeCell: UICollectionViewCell {
    
    weak var delegate: WBComposeCellDelegate?
    
    
    
    /// image属性
    var image: UIImage? {
        didSet {
            if let image = image {
                addOrChangeButton.setBackgroundImage(image, for: .normal)
                deleteButton.isHidden = false
            } else {
                addOrChangeButton.setBackgroundImage(UIImage(named: "compose_pic_add"), for: .normal)
                deleteButton.isHidden = true
            }
        }
    }
    
    /// 添加或替换图片的按钮
//    lazy var addOrChangeButton: UIButton = UIButton(text: nil, bgImage: "compose_pic_add", target: self, selector: #selector(addOrChangeImage))
    lazy var addOrChangeButton: UIButton = {
        UIButton(text: nil, bgImage: "compose_pic_add", target: self, selector: #selector(addOrChangeImage))
    }()
    
    /// 删除图片的按钮
    lazy var deleteButton: UIButton = UIButton(text: nil, bgImage: "compose_photo_close", target: self, selector: #selector(deleteImage))

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

extension WBComposeCell {
    func setupUI () {
        //1. 添加子视图
        self.contentView.addSubview(addOrChangeButton)
        self.contentView.addSubview(deleteButton)
        
        //2. 自动布局
        addOrChangeButton.snp.makeConstraints { (make) in
            make.top.left.equalTo(self.contentView).offset(10)
            make.right.bottom.equalTo(self.contentView).offset(-10)
        }
        
        deleteButton.snp.makeConstraints { (make) in
            make.left.equalTo(addOrChangeButton.snp.right).offset(-13)
            make.bottom.equalTo(addOrChangeButton.snp.top).offset(13)
            make.size.equalTo(CGSize(width: 25, height: 25))
        }
    }
}

extension WBComposeCell {
    @objc func addOrChangeImage() {
        delegate?.addOrChangeImage(cell: self)
    }
    
    @objc func deleteImage() {
        delegate?.deleteImage(cell: self)
    }
}
